(function() {

    var session_poll_interval = 5000;

    var session_expiration_minutes = 3;

    var session_intervalId, session_last_time;

    // 初始化监听
    function initMonitor () {
        session_last_time = new Date();
        sessionSetInterval();
        var last_time_setTimeout;
        $(document).on('mouseover keydown', function () {
            clearTimeout(last_time_setTimeout);
            last_time_setTimeout = setTimeout(function () {
                session_last_time = new Date();
            }, 200);
        });
    }

    // 设置session监听循环
    function sessionSetInterval () {
        session_intervalId = setInterval(sessionInterval, session_poll_interval);
    }

    // 清除Interval循环
    function sessionClearInterval() {
        clearInterval(session_intervalId);
    }

    // session过期后处理的事情
    function sessionTimeout () {
        $.post(g.ctx + 'logout', function () {
            window.location.href = g.ctx + 'login';
        });
    }

    function sessionInterval () {
        var now = new Date();
        var diff = now - session_last_time;
        var diffMins = (diff / 1000 / 60);

        // 超时
        if (diffMins >= session_expiration_minutes) {
            sessionClearInterval();
            sessionTimeout();
        }
    }

    initMonitor();

})();

